#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <fcntl.h>
#include <io.h>
#include <stdio.h>
#include "iostream"

#ifdef unix
# include <unistd.h>
# include <utime.h>
#else
# include <direct.h>
# include <io.h>
#endif

#include "miniunz.h"
#include "unzip.h"
#include "UnzipDocx.h"
#define MAXFILENAME (256)

int UnzipDocx ::open_zipfile(){
	 if (zipfilename!=NULL)
			{

				#        ifdef USEWIN32IOAPI
						zlib_filefunc_def ffunc;
				#        endif

				strncpy(filename_try, zipfilename,MAXFILENAME-1);
				/* strncpy doesnt append the trailing NULL, of the string is too long. */
				filename_try[ MAXFILENAME ] = '\0';

				#        ifdef USEWIN32IOAPI
						fill_win32_filefunc(&ffunc);
						uf = unzOpen2(zipfilename,&ffunc);
				#        else
						uf = unzOpen(zipfilename);
				#        endif
				if (uf==NULL)
				{
					strcat(filename_try,".zip");
						#            ifdef USEWIN32IOAPI
									uf = unzOpen2(filename_try,&ffunc);
						#            else
									uf = unzOpen(filename_try);
						#            endif
				}
			}

			if (uf==NULL)
			{
				//printf("Cannot open %s or %s.zip\n",zipfilename,zipfilename);
				return 1;
			}
			//printf("%s opened\n",filename_try);
			return 0;
}



void UnzipDocx ::close_zipfile(){
	unzCloseCurrentFile(uf);
}

UnzipDocx ::UnzipDocx(){
		zipfilename=NULL;
		filename_to_extract=NULL;
		password=NULL;
		dirname=NULL;
		uf=NULL;
}

UnzipDocx :: UnzipDocx(char *zipfile){
		zipfilename = zipfile;
	}

UnzipDocx :: UnzipDocx(char *zipfile,char *dir){
		zipfilename = zipfile;
		dirname = dir;
		//dirname = getDirectoryName(zipfile);
	}

UnzipDocx :: UnzipDocx(char *zipfile,char *dir,char *file_to_extract){
		zipfilename = zipfile;
		dirname = dir;
		filename_to_extract = file_to_extract;
	}


void UnzipDocx :: get_file_list(){
		if(open_zipfile() == 0)
			 do_list(uf);
		close_zipfile();
	}

bool UnzipDocx :: extract_all_files(){
		//char * path = "C:\Temp\\" ;
		//strcat(path,dirname);
		//dirname = getDirectoryName(zipfilename);
		if(open_zipfile() == 0){
			//if(mkdir(dirname)==-1)//creating a directory
			// {
			//	//cerr<<"Error :  "<<strerror(errno)<<endl;
			//	 printf("Error changing into %s, aborting\n", dirname);
			//	exit(1);
			// }

			if (chdir(dirname)) 
			{
				printf("Error changing into %s, aborting\n", dirname);
				exit(-1);
			}
			if(do_extract(uf,0,0,NULL)== -1){
				return false;
			}
		}
		else
		{
			return false;
		}
		close_zipfile();
		return true;
	}

void UnzipDocx :: extract_single_file(){
		if(open_zipfile() == 0){
			if (chdir(dirname)) 
			{
				//printf("Error changing into %s, aborting\n", dirname);
				exit(-1);
			}
			do_extract_onefile(uf,filename_to_extract,0,0,NULL);
		}
		close_zipfile();
	}